package com.situ.mallsdauweb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.situ.mallsdauweb.entity.Member;
import com.situ.mallsdauweb.entity.OrderInfo;
import com.situ.mallsdauweb.service.IOrderAddressService;
import com.situ.mallsdauweb.service.IOrderInfoService;
import com.situ.mallsdauweb.service.IPayService;
import com.situ.mallsdauweb.vo.OrderInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private IPayService payService;

    @PostMapping("/save")
    public String saveOrder(Integer addId, String cartIds, Model model) {
        //返回订单表的主键
        Integer id = orderInfoService.saveOrder(addId, cartIds);
        //根据订单主键获取支付二维码
        try {
        String qrCode = payService.pay(id);
        model.addAttribute("qrCode", qrCode);
        model.addAttribute("id",id);
    }catch (Exception e) {
        e.printStackTrace();
        System.out.println("对接支付宝失败，未获得二维码");
    }
        //提示订单生成成功，可以付款
        return "payment";
    }

    @ResponseBody
    @GetMapping("/status")
    public String status(Integer id){
        OrderInfo oi = orderInfoService.getById(id);
        return oi.getStatus();
    }

    @GetMapping("orders")
    @ResponseBody
    public List<OrderInfoVO> orders(String status,HttpSession session) {
        Member current = (Member) session.getAttribute("current");
        Integer id = current.getId();
        status = "0";
        List<OrderInfoVO> orderInfoVOS = orderInfoService.selectOrders(id, status);
        return orderInfoVOS;

    }

    @JmsListener(destination = "order.save")
    public void checkStatus(Integer id) {
        // 根据订单ID查询订单
        //判断是否还是未支付状态
        OrderInfo oi = orderInfoService.getById(id);
        if ("待支付".equals(oi.getStatus())){
            orderInfoService.updateStatus(oi.getCode(),"已取消");
        }
    }


}
